import {
	ajax
} from '../../../../common/plus.util.js'

import htmlparser2, {
	DomUtils
} from 'htmlparser2'


//#region 资源页面解析
class resourceParser {

	parse() {
		// 私有方法
		function html2JsonObj(str) {
			let dom = null

			try {
				dom = htmlparser2.parseDOM(str);
			} catch (e) {
				console.log(e)
			}
			const resources = DomUtils.findAll(element => {
				const matches = element.name === 'article' && element.attribs.class ===
					'excerpt excerpt-one';
				return matches;
			}, dom);

			let currentPageSource = []
			let nextPageUrl = ''
			let prevPageUrl = ''
			const nextPageEl = DomUtils.findOne(e => e.name === 'li' && e.attribs.class === 'next-page',
				dom);
			if (nextPageEl) {
				const nextAEl = DomUtils.findOne(e => e.name === 'a', nextPageEl.children);
				if (nextAEl) {
					nextPageUrl = '/' + nextAEl.attribs.href;
				}
			}
			const prevPageEl = DomUtils.findOne(e => e.name === 'li' && e.attribs.class === 'prev-page',
				dom);
			if (prevPageEl) {
				const prevAEl = DomUtils.findOne(e => e.name === 'a', prevPageEl.children);
				if (prevAEl) {
					prevPageUrl = '/' + prevAEl.attribs.href;
				}
			}

			resources.forEach(resource => {
				const header = DomUtils.findOne(e => e.name === 'header', resource.children)
				let title = ''
				let url = ''
				let img = ''
				if (header) {
					let aEl = DomUtils.findOne(e => e.name === 'a' && e.attribs.target ===
						'_blank',
						header
						.children)
					if (aEl) {
						title = aEl.attribs.title
						url = aEl.attribs.href
					}
				}
				let imgEl = DomUtils.findOne(e => e.name === 'img', resource.children)
				if (imgEl) {
					img = imgEl.attribs.src
				}
				currentPageSource.push({
					title,
					url,
					img
				})
			})
			console.log(`本页共${currentPageSource.length}个资源`)
			console.log(`上一页：${prevPageUrl}`)
			console.log(`下一页：${nextPageUrl}`)
			return {
				resources: currentPageSource,
				prevPageUrl,
				nextPageUrl
			}
		}




		const me = this
		return new Promise((resolve, reject) => {
			console.log(me.url);
			ajax({
				url: me.url,
				method: 'GET',
				data: null,
				success(text) {
					console.log('请求成功：');
					const result = html2JsonObj(text)
					me.onprogress()
					me.oncomplete(result)
					resolve(result)
				},
				error(xhr, textStatus, error) {
					console.log('请求失败：' + textStatus);
					reject('请求失败：' + textStatus);
				}
			})
		})
	}

	constructor(url, oncomplete = function() {}, onprogress = () => {}) {
		this.url = url
		this.oncomplete = oncomplete
		this.onprogress = onprogress
	}
}
//#endregion


//#region 详情页面解析
class detailParser {

	parse() {
		// 私有方法
		function html2JsonObj(str) {

			const detailDom = htmlparser2.parseDOM(str);
			//#region 本页图片解析
			const imgUrls = []
			const detailResourceArticleEl = DomUtils.findOne(element => {
				return element.name === 'article' && element.attribs.class === 'article-content';
			}, detailDom);

			if (detailResourceArticleEl) {
				DomUtils.findAll(element => {
					if (element.name === 'img') {
						imgUrls.push(element.attribs.src)
					}
					return true
				}, detailResourceArticleEl.children);
			}


			//#endregionf

			//#region 下一页url解析

			let detailNextPageUrl = ''
			const detailNextPageEl = DomUtils.findOne(e => e.name === 'li' && e.attribs.class ===
				'next-page',
				detailDom);

			if (detailNextPageEl) {
				const nextAEl = DomUtils.findOne(e => e.name === 'a', detailNextPageEl.children);
				if (nextAEl) {
					detailNextPageUrl = (nextAEl.attribs.href.startsWith('/') ? '' : '/') + nextAEl.attribs.href;
				}
			}
			//#endregion 
			console.log(`本页共${imgUrls.length}个图片`)
			// console.log(imgUrls)
			console.log(`下一页：${detailNextPageUrl}`)
			if (imgUrls.length === 0) {
				// 如果本页都没有资源，那就应该是无效资源。直接跳出。
				detailNextPageUrl = ''
				console.log('无效资源')
			}
			return {
				resources: imgUrls,
				nextPageUrl: detailNextPageUrl
			}
		}



		const me = this
		return new Promise((resolve, reject) => {
			const allResult = []

			function doTask(url) {
				ajax({
					url: url,
					method: 'GET',
					data: null,
					success(text) {
						console.log('请求成功：');
						const result = html2JsonObj(text)
						me.onprogress(result)
						allResult.push(result)
						if (result.resources.length > 0 && result.nextPageUrl.length > 0) {
							console.log('nextUrl' + me.baseUrl + result.nextPageUrl)
							doTask(me.baseUrl + result.nextPageUrl);
						} else {
							me.oncomplete(allResult);
							resolve(allResult);
						}
					},
					error(xhr, textStatus, error) {
						console.log('请求失败：' + textStatus);
						reject('请求失败：' + textStatus);
					}
				})
			}
			doTask(me.url);


		})
	}

	constructor(url, oncomplete = function() {}, onprogress = () => {}) {
		this.url = url

		function parseBaseUrl(l) {
			return l.substring(0, l.lastIndexOf('/'));
		}
		this.baseUrl = parseBaseUrl(url);
		this.oncomplete = oncomplete
		this.onprogress = onprogress
	}
}
//#endregion

/**
 * 解析器出口
 */
export default {
	// // 工厂
	resourceParser,
	detailParser
}
